package com.zhx.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @program: web-framework
 * @author: zhx
 * @create: 2021-03-20 18:35
 **/
public class JspFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
        HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
        String requestURI = servletRequest1.getRequestURI();
        String servletPath = requestURI.substring(requestURI.lastIndexOf('/') + 1);
        String contextPath = servletRequest1.getContextPath();
        if(requestURI!=null && servletPath.equals("Login.jsp") || servletPath.equals("login") || servletPath.equals("login.html")){
            servletResponse1.sendRedirect(contextPath+"/Login.html");
            return;
        }
        if(servletPath.endsWith(".jsp")){
            servletResponse1.sendRedirect(contextPath+"/notfount.html");
        }
        HttpSession session = servletRequest1.getSession(false);
        if (session == null && !servletPath.equals("Login.html")){
            //说明session过期了
            servletResponse1.sendRedirect(contextPath+"/Login.html");
            return;
        }
        filterChain.doFilter(servletRequest1, servletResponse1);
    }

    @Override
    public void destroy() {

    }
}
